<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "UserCollection".
 */
class UserCollection extends ActiveRecord {

    // 收藏类型
    const TypeRecruit = 1;
    const TypeDesigner = 2;
    const TypeDesign = 3;
    public static $typeSelector = [
        self::TypeRecruit => ['title' => '招聘', 'status' => 'green'],
        self::TypeDesigner => ['title' => '设计师', 'status' => 'blue'],
        self::TypeDesign => ['title' => '设计作品', 'status' => 'orange'],
    ];

    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['user_id', 'collection_id', 'type'], 'required'],
            [['user_id', 'collection_id', 'type'], 'integer'],
        ];
    }
    /**
     * 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户',
            'collection_id' => '来源编号',
            'type' => '收藏类型',
        ];
    }

    /**
     * 获取user信息
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
     * 获取招聘信息
     * @return \yii\db\ActiveQuery
     */
    public function getRecruit()
    {
        return $this->hasOne(Recruit::className(), ['id' => 'collection_id']);
    }

    /**
     * 获取作品信息
     * @return \yii\db\ActiveQuery
     */
    public function getDesign()
    {
        return $this->hasOne(Design::className(), ['id' => 'collection_id']);
    }
    
    /**
     * 获取user信息
     * @return \yii\db\ActiveQuery
     */
    public function getDesigner()
    {
        return $this->hasOne(User::className(), ['id' => 'collection_id']);
    }
    
    /**
     * 创建收藏记录
     * @return mixed
     */
    public static function creator($params)
    {
        if(empty($params)) {
            return false;
        }
        $collection = new static();
        $collection->user_id = Yii::$app->user->id;
        $collection->loads($params);
        if( ! ($collection->validate() && $collection->save())) {
            return false;
        }
        // 添加收藏次数
        if($collection->type == static::TypeRecruit) {
            $collection->recruit->browser();
        }
        else if($collection->type == static::TypeDesign) {
            $collection->design->browser();
        }
        return $collection;
    }
    
    /**
     * 删除收藏记录
     * @return boolean
     */
    public function delete()
    {
        if(parent::delete()) {
            // 扣除收藏次数
            if($this->type == static::TypeRecruit) {
                $this->recruit->browser();
            }
            else if($this->type == static::TypeDesign) {
                $this->design->browser();
            }
            return true;
        }
        return false;
    }
}